﻿using System;
using System.IO;
using System.Web.UI.WebControls;
using Resources;
using Yglu.BusinessLayer;
using Yglu.BusinessLayer.Entities;
using Yglu.BusinessLayer.Enums;
using Yglu.BusinessLayer.Reports;

namespace Yglu.WebAdmin
{
	public partial class Products_aspx : BasePage
	{
		#region Main methods

		protected void Page_Load(object sender, EventArgs e)
		{
			CheckPermissions(AdminLevel.Store);

			if (!IsPostBack)
			{
				PanEdit.Visible = false;

				SetDefaults();
			}
		}

		protected void Page_PreRender(Object sender, EventArgs e)
		{
			if (PanGrid.Visible)
			{
				LoadData();
			}

			PlaceReports.Visible = PanEdit.Visible && TxtProductId.Text != "0";
		}

		private void SetDefaults()
		{
			SetDefaults(GridProducts);
			SetDefaults(GridReports);

			TxtProductId.Enabled = false;

			if (SessionManager.LoggedUser.AdminLevel >= AdminLevel.Company)
			{
				CboStore.DataSource = Settings.Stores;
				CboStore.DataBind();
			}
			else
			{
				ButAddNew.Visible = false;
				CboStore.Enabled = false;

				CboStore.Items.Add(new ListItem(SessionManager.LoggedStore.Title, SessionManager.LoggedStore.Id.ToString()));
			}

			CboStore.Items.Insert(0, new ListItem(Messages.AllStores, "0"));
			CboStore.SelectedValue = SessionManager.LoggedStore.Id.ToString();
		}

		private void LoadData()
		{
			if (SessionManager.LoggedStore.Id > 0)
			{
				CboCategory.DataSource = new CategoryCollection(DataAccess.Category_Get(SessionManager.LoggedStore));
				GridProducts.DataSource = new ProductCollection(DataAccess.Product_Get(SessionManager.LoggedStore));
			}
			else
			{
				CboCategory.DataSource = new CategoryCollection(DataAccess.Category_Get());
				GridProducts.DataSource = new ProductCollection(DataAccess.Product_Get());
			}
            
			CboCategory.DataBind();
            GridProducts.DataBind();

			LblGridCount.Text = GetLocalResourceObject("LblGridCount.Text").ToString().Replace("#", GridProducts.Rows.Count.ToString());

			PanEdit.Visible = false;
			PanGrid.Visible = true;
		}

		#endregion

		#region Add and edit

		protected void ButAddNew_Click(Object sender, EventArgs e)
		{
			TxtProductId.Text = "0";
			TxtProductTitle.Text = String.Empty;
			TxtProductPrice.Text = String.Empty;
			CboCategory.Enabled = true;
            ChkProductActive.Checked = true;

			ImgProductIcon.ImageUrl = Settings.SystemConfig.ProductIconsUrl + "0.png";

			LitEditLegend.Text = GetLocalResourceObject("LitAddProduct.Text").ToString();
			PanEdit.Visible = true;
			PanGrid.Visible = false;
		}

		protected void GridProducts_RowCommand(Object sender, GridViewCommandEventArgs e)
		{
			EditProduct(Convert.ToInt32(e.CommandArgument));
		}

		private void EditProduct(Int32 row)
		{
			Int32 id = Convert.ToInt32(GridProducts.Rows[row].Cells[0].Text);
			Product p = new Product(id);

			TxtProductId.Text = p.Id.ToString();
			TxtProductTitle.Text = p.Title;
			TxtProductPrice.Text = p.Price.ToString("0.00");
			ChkProductActive.Checked = p.Active;
            CboCategory.SelectedValue = p.Category.Id.ToString();
			CboStore.SelectedValue = p.StoreId.ToString();

			if (File.Exists(Settings.SystemConfig.ProductIconsPath + p.Id + ".png"))
			{
				ImgProductIcon.ImageUrl = Settings.SystemConfig.ProductIconsUrl + p.Id + ".png";
			}
			else
			{
				ImgProductIcon.ImageUrl = Settings.SystemConfig.ProductIconsUrl + "0.png";
			}

			if (SessionManager.LoggedUser.AdminLevel < AdminLevel.Company)
			{
				CboCategory.Enabled = false;
			}
			else
			{
				CboCategory.Enabled = true;
			}
			
            LitEditLegend.Text = GetLocalResourceObject("LitEditProduct.Text").ToString();
            PanEdit.Visible = true;
			PanGrid.Visible = false;

			LoadReports(p);
		}

		private void LoadReports(Product p)
		{
			ProductOrdersCollection reports = ReportManager.GetProductOrders(p.Id);

			GridReports.DataSource = reports;
			GridReports.DataBind();
		}

		#endregion

		#region Save to database

		protected void ButSave_Click(Object sender, EventArgs e)
		{
			Page.Validate();

			if (!Page.IsValid)
			{
				return;
			}

			Product p = new Product(Convert.ToInt32(TxtProductId.Text));

			try
			{
				p.Title = TxtProductTitle.Text.Trim();
				p.Price = Convert.ToDouble(TxtProductPrice.Text);
				p.Active = ChkProductActive.Checked;

				p.Category = new Category(Convert.ToInt32(CboCategory.SelectedValue));

				if (CboStore.SelectedValue == "0")
				{
					p.AllStores = true;
				}
				else
				{
					p.StoreId = Convert.ToInt32(CboStore.SelectedValue);
				}

				try
				{
					DataAccess.Product_Upsert(p);

					TxtProductId.Text = p.Id.ToString();

					ClientScript.RegisterStartupScript(typeof(String), "ProductSaved", "YgluTopAlert('" + Messages.ConfirmationDataSaved + "', true);", true);

					PanGrid.Visible = true;
				}
				catch (Exception ex)
				{
					Master.SetError(ex, Messages.ErrorCouldNotSaveData);
				}
			}
			catch (Exception ex)
			{
				Master.SetError(ex, Messages.ErrorInvalidForm);
			}
		}

		protected void ButCancel_Click(Object sender, EventArgs e)
		{
			PanEdit.Visible = false;
			PanGrid.Visible = true;
		}

		#endregion
	}
}